# script_storage.py - 完全重写数据库操作
import logging
import os
import json
from db_pool import get_db_connection
from config import Config

logger = logging.getLogger('script_storage')


class ScriptStorage:
    def __init__(self):
        self.storage_type = Config.SCRIPT_STORAGE

    def save_script(self, api_id, script_content):
        """保存脚本 - 确保原子性操作"""
        if self.storage_type == 'file':
            return self._save_to_file(api_id, script_content)
        else:
            return self._save_to_database(api_id, script_content)

    def load_script(self, api_id):
        """加载脚本"""
        if self.storage_type == 'file':
            return self._load_from_file(api_id)
        else:
            return self._load_from_database(api_id)

    def delete_script(self, api_id):
        """删除脚本"""
        if self.storage_type == 'file':
            return self._delete_from_file(api_id)
        else:
            return self._delete_from_database(api_id)

    def script_exists(self, api_id):
        """检查脚本是否存在"""
        if self.storage_type == 'file':
            return self._file_exists(api_id)
        else:
            return self._database_exists(api_id)

    def _save_to_file(self, api_id, script_content):
        """保存到文件"""
        script_path = os.path.join(Config.API_DIR, f'{api_id}.py')
        try:
            with open(script_path, 'w', encoding='utf-8') as f:
                f.write(script_content)
            return True, None
        except Exception as e:
            logger.error(f"Failed to save script to file: {str(e)}")
            return False, str(e)

    def _load_from_file(self, api_id):
        """从文件加载"""
        script_path = os.path.join(Config.API_DIR, f'{api_id}.py')
        if not os.path.exists(script_path):
            return None, f"Script file not found: {api_id}.py"

        try:
            with open(script_path, 'r', encoding='utf-8') as f:
                return f.read(), None
        except Exception as e:
            logger.error(f"Failed to load script from file: {str(e)}")
            return None, str(e)

    def _delete_from_file(self, api_id):
        """从文件删除"""
        script_path = os.path.join(Config.API_DIR, f'{api_id}.py')
        if os.path.exists(script_path):
            try:
                os.remove(script_path)
                return True, None
            except Exception as e:
                logger.error(f"Failed to delete script file: {str(e)}")
                return False, str(e)
        return True, None

    def _file_exists(self, api_id):
        """检查文件是否存在"""
        script_path = os.path.join(Config.API_DIR, f'{api_id}.py')
        return os.path.exists(script_path)

    def _save_to_database(self, api_id, script_content):
        """保存到数据库 - 修复版本"""
        connection = None
        try:
            logger.info(f"Saving script to database for API: {api_id}")
            connection = get_db_connection()
            cursor = connection.cursor()

            # 检查是否已存在
            cursor.execute(f"SELECT id FROM {Config.SCRIPTS_TABLE} WHERE api_id = %s", (api_id,))
            result = cursor.fetchone()

            if result:
                # 更新现有记录
                logger.info(f"Updating existing script for API: {api_id}")
                cursor.execute(
                    f"UPDATE {Config.SCRIPTS_TABLE} SET script_content = %s, updated_at = NOW() WHERE api_id = %s",
                    (script_content, api_id)
                )
            else:
                # 插入新记录
                logger.info(f"Inserting new script for API: {api_id}")
                cursor.execute(
                    f"INSERT INTO {Config.SCRIPTS_TABLE} (api_id, script_content) VALUES (%s, %s)",
                    (api_id, script_content)
                )

            connection.commit()
            logger.info(f"Script saved successfully for API: {api_id}")
            return True, None

        except Exception as e:
            logger.error(f"Database error while saving script: {str(e)}")
            if connection:
                connection.rollback()
            return False, f"Database error: {str(e)}"
        finally:
            if connection:
                connection.close()

    def _load_from_database(self, api_id):
        """从数据库加载 - 修复版本"""
        connection = None
        try:
            logger.info(f"Loading script from database for API: {api_id}")
            connection = get_db_connection()
            cursor = connection.cursor()

            cursor.execute(
                f"SELECT script_content FROM {Config.SCRIPTS_TABLE} WHERE api_id = %s",
                (api_id,)
            )
            result = cursor.fetchone()

            if result:
                script_content = result['script_content'] if 'script_content' in result else result[0]
                logger.info(f"Script loaded successfully for API: {api_id}")
                return script_content, None
            else:
                error_msg = f"Script not found in database for API: {api_id}"
                logger.error(error_msg)
                return None, error_msg

        except Exception as e:
            error_msg = f"Database error while loading script: {str(e)}"
            logger.error(error_msg)
            return None, error_msg
        finally:
            if connection:
                connection.close()

    def _delete_from_database(self, api_id):
        """从数据库删除"""
        connection = None
        try:
            connection = get_db_connection()
            cursor = connection.cursor()

            cursor.execute(
                f"DELETE FROM {Config.SCRIPTS_TABLE} WHERE api_id = %s",
                (api_id,)
            )

            connection.commit()
            return True, None
        except Exception as e:
            logger.error(f"Failed to delete script from database: {str(e)}")
            if connection:
                connection.rollback()
            return False, str(e)
        finally:
            if connection:
                connection.close()

    def _database_exists(self, api_id):
        """检查数据库记录是否存在"""
        connection = None
        try:
            connection = get_db_connection()
            cursor = connection.cursor()

            cursor.execute(
                f"SELECT id FROM {Config.SCRIPTS_TABLE} WHERE api_id = %s",
                (api_id,)
            )
            result = cursor.fetchone()
            return result is not None
        except Exception as e:
            logger.error(f"Failed to check script existence in database: {str(e)}")
            return False
        finally:
            if connection:
                connection.close()


# 创建全局存储实例
script_storage = ScriptStorage()